package MRdemo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;

public class JobFile extends Configured implements Tool {
    private static final Log logger = LogFactory.getLog(JobFile.class);
    public int run(String[] args) throws Exception {

        Configuration conf = this.getConf();
        Job job = Job.getInstance();

        job.setJarByClass(getClass());

        job.setJobName(this.getClass().getSimpleName());
        job.setMapperClass(MapperFile.class);
        job.setReducerClass(ReducerFile.class);

        job.setMapOutputKeyClass(ReWriteKey.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(Text.class);



        FileInputFormat.setMaxInputSplitSize(job, 1024 * 1024 * 16L);

        FileSystem fileSystem = FileSystem.get(conf);

        //输入路径
        FileStatus[] fileStatus = fileSystem.globStatus(new Path(conf.get("INPUT_PATH") + "/*.txt"));
        for (FileStatus status : fileStatus) {
            Path inputpath = new Path(status.getPath().toString());
            if (fileSystem.isFile(inputpath)) {
                FileInputFormat.addInputPath(job, inputpath);
            }
        }

        //输出路径
        Path outputDir = new Path(conf.get("OUTPUT_PATH"));
        if (fileSystem.exists(outputDir)){
            fileSystem.delete(outputDir,true);
        }
        fileSystem.close();
        FileOutputFormat.setOutputPath(job, outputDir);

        //提交作业
        job.waitForCompletion(true);
        return 0;
    }
}
